/**
 *
 * @(#) MD5.java
 * @Package com.ls.ner.pub.util
 *
 * Copyright © Longshine Corporation. All rights reserved.
 *
 */

package com.nft.utils.common;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.*;

/**
 *  Description :
 *
 *  @author:  hemingming
 *
 *  History:  2016年3月29日 下午9:10:41   hemingming   Created.
 *
 */
public class MD5 {
	public static final String charset = "UTF-8";
	/**
     * 签名字符串
     * @param text 需要签名的字符串
     * @param key 密钥
     * @param input_charset 编码格式
     * @return 签名结果
     */
    public static String sign(String text, String key, String input_charset) {
    	text = text + key;
        return DigestUtils.md5Hex(getContentBytes(text, input_charset));
    }

    /**
     * 签名字符串
     * @param text 需要签名的字符串
     * @param sign 签名结果
     * @param key 密钥
     * @param input_charset 编码格式
     * @return 签名结果
     */
    public static boolean verify(String text, String sign, String key, String input_charset) {
    	text = text + key;
    	String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
    	if(mysign.equals(sign)) {
    		return true;
    	}
    	else {
    		return false;
    	}
    }

    /**
     * @param content
     * @param charset
     * @return
     * @throws SignatureException
     * @throws UnsupportedEncodingException
     */
    private static byte[] getContentBytes(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }
        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
        }
    }

	private static String byteArrayToHexString(byte b[]) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; i++)
			resultSb.append(byteToHexString(b[i]));

		return resultSb.toString();
	}

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0)
			n += 256;
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	public static String MD5Encode(String origin, String charsetname) {
		String resultString = null;
		try {
			resultString = new String(origin);
			MessageDigest md = MessageDigest.getInstance("MD5");
			if (charsetname == null || "".equals(charsetname))
				resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
			else
				resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
		} catch (Exception exception) {
		}
		return resultString;
	}

	/**
	 *
	 * Method description : 跟客户端加密方法一致
	 *
	 * Author：        lipf
	 * Create Date：   2015年9月10日 下午9:05:12
	 * History:  2015年9月10日 下午9:05:12   lipf   Created.
	 *
	 * @param plainText
	 * @return
	 *
	 */
	public static String getMd5_16(String plainText) {
		StringBuffer buf = new StringBuffer();
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");

			md.update(plainText.getBytes());
			byte b[] = md.digest();
			int i;
			buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return buf.toString().substring(8, 24);
	}

	/**
	 * MD5加密
	 *
	 * @param inStr
	 * @return
	 */
	public static String MD5Str(String inStr) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		char[] charArray = inStr.toCharArray();
		byte[] byteArray = new byte[charArray.length];

		for (int i = 0; i < charArray.length; i++) {
			byteArray[i] = (byte) charArray[i];
		}
		byte[] md5Bytes = md5.digest(byteArray);

		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16)
				hexValue.append("0");
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}

	public static String md5PassWord(String code) {
		return org.springframework.util.DigestUtils.md5DigestAsHex(code.getBytes());
	}

	/**
	 * @param inStr
	 * @description md5加密 加UTF-8编码
	 * @author tianyoupeng
	 * @create 2018-06-13 09:41:24
	 */
	public static String MD5StrUTF8(String inStr) {
		try {
			byte[] btInput = inStr.getBytes(charset);
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			mdInst.update(btInput);
			byte[] md = mdInst.digest();
			StringBuffer sb = new StringBuffer();
			for(int i = 0; i < md.length; i++) {
				int val = ((int) md[i]) & 0xff;
				if(val < 16){
					sb.append("0");
				}
				sb.append(Integer.toHexString(val));
			}
			return sb.toString();
		} catch(Exception e) {
			return null;
		}
	}

	/**
	 * @param key
	 * @param parameters
	 * @description 对map中的内容进行md5加密
	 * @author wenqiangl
	 * @create 2018-05-18 10:56:05
	 */
	public static String createSign(String key, SortedMap<String, Object> parameters) {
		StringBuffer sb = new StringBuffer();
		Set es = parameters.entrySet();// 所有参与传参的参数按照ASCII排序（升序）
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			Object v = entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + key);
		String sign = MD5Encode(sb.toString(), charset).toUpperCase();
		return sign;
	}

	// 50位0
	private final static String SALT = "00000000000000000000000000000000000000000000000000";
	/**
	 * 加盐方式 md5
	 * @param pswd 密码
	 * @return 加密串
	 */
	public static String MD5Salt(String pswd) {
		String inStr = pswd + SALT;
		return MD5Str(inStr);
	}

	private static final String hexDigits[] = { "0", "1", "2",
		"3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

	public static void main(String[] args) {
		System.out.println(MD5Str("apiKey=ptb1e6884f4603f08a&nonceStr=7aZHeEeLgSoFG9IC&timestamp=1535427198000&key=44ed56fc77ed4e4cafa65ced63a04010").toUpperCase());
		System.out.println(System.currentTimeMillis());

		SortedMap<String, Object> map = new TreeMap<String, Object>();
		map.put("apiKey", "pta03d7c1824087d4e");
		map.put("timestamp", "1535621377557");
		map.put("nonceStr", "7aZHeEeLgSoFG9IC");
		System.out.print(createSign("a559e9e963794eeb8f62d2fbaa50110c",map));
	}

}
